package com.sqfw.framework.security.provider;

import com.sqfw.framework.security.authentication.CodeAuthenticationToken;
import com.sqfw.project.system.service.UserDetailsService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

public class CodeAuthenticationProvider extends AbstractAuthenticationProvider {

    public CodeAuthenticationProvider(UserDetailsService userDetailsService) {
        super(userDetailsService);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(CodeAuthenticationToken.class, authentication, "only support card");
        String code = authentication.getPrincipal() == null ? "Unknown" : authentication.getName();
        UserDetails user = getUserDetailsService().loadUserByCode(code);
        checkUser(user);
        return new CodeAuthenticationToken(user, mapAuthorities(user.getAuthorities()));
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return CodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
